package org.jeecg.modules.common.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.config.TenantContext;
import org.jeecg.common.constant.SymbolConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.ImportExcelUtil;
import org.jeecg.common.util.SqlInjectionUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.config.mybatis.MybatisPlusSaasConfig;
import org.jeecg.modules.common.entity.CommonClassify;
import org.jeecg.modules.common.mapper.CommonClassifyMapper;
import org.jeecg.modules.common.service.ICommonClassifyService;
import org.jeecg.modules.common.vo.CommonClassifyVO;
import org.jeecg.modules.common.vo.TreeSelectModel;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 分类管理
 * @Author: jeecg-boot
 * @Date: 2023-08-13
 * @Version: V1.0
 */
@Service
@Slf4j
public class CommonClassifyServiceImpl extends ServiceImpl<CommonClassifyMapper, CommonClassify> implements ICommonClassifyService {

    @Override
    public IPage<CommonClassifyVO> page(CommonClassify commonClassify, Integer pageNo, Integer pageSize, HttpServletRequest req) {
        QueryWrapper<CommonClassify> queryWrapper = QueryGenerator.initQueryWrapper(commonClassify, req.getParameterMap());
        Page<CommonClassify> page = new Page<>(pageNo, pageSize);
        Page<CommonClassify> page1 = page(page, queryWrapper);
        Page<CommonClassifyVO> pageVo = new Page<>();
        BeanUtils.copyProperties(page1, pageVo);
        List<CommonClassify> records = page1.getRecords();
        List<String> ids = records.stream().map(CommonClassify::getId).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(ids)) {
            List<CommonClassify> commonClassifies = listByIds(ids);
            List<CommonClassifyVO> classifyVOS = records.stream().map(s -> {
                CommonClassifyVO vo = new CommonClassifyVO();
                BeanUtils.copyProperties(s, vo);
                if (vo.getPid() != null) {
                    CommonClassify commonClassify1 = commonClassifies.stream().filter(c -> c.getId().equals(vo.getPid())).findFirst().orElse(null);
                    if (commonClassify1 != null) {
                        vo.setParentName(commonClassify1.getName());
                    }
                }
                return vo;
            }).collect(Collectors.toList());
            pageVo.setRecords(classifyVOS);
        }
        return pageVo;
    }


    @Override
    public void addCommonClassify(CommonClassify commonClassify) {
        String categoryPid = ICommonClassifyService.ROOT_PID_VALUE;
        if (oConvertUtils.isNotEmpty(commonClassify.getPid())) {
            categoryPid = commonClassify.getPid();

            //PID 不是根节点 说明需要设置父节点 hasChild 为1
            if (!ICommonClassifyService.ROOT_PID_VALUE.equals(categoryPid)) {
                CommonClassify parent = baseMapper.selectById(categoryPid);
                if (parent != null && !ICommonClassifyService.HAS_CHILD.equals(parent.getHasChild())) {
                    parent.setHasChild(ICommonClassifyService.HAS_CHILD);
                    baseMapper.updateById(parent);
                }
            }
        }
        //update-begin--Author:baihailong  Date:20191209 for：分类字典编码规则生成器做成公用配置
        commonClassify.setPid(categoryPid);
        baseMapper.insert(commonClassify);
    }

    @Override
    public void updateCommonClassify(CommonClassify commonClassify) {
        if (oConvertUtils.isEmpty(commonClassify.getPid())) {
            commonClassify.setPid(ICommonClassifyService.ROOT_PID_VALUE);
        } else {
            //如果当前节点父ID不为空 则设置父节点的hasChild 为1
            CommonClassify parent = baseMapper.selectById(commonClassify.getPid());
            if (parent != null && !ICommonClassifyService.HAS_CHILD.equals(parent.getHasChild())) {
                parent.setHasChild(ICommonClassifyService.HAS_CHILD);
                baseMapper.updateById(parent);
            }
        }
        baseMapper.updateById(commonClassify);
    }

    @Override
    public List<TreeSelectModel> queryListByCode(String pid) throws JeecgBootException {
        pid = StringUtils.isBlank(pid) ? ROOT_PID_VALUE : pid;
        return baseMapper.queryListByPid(pid, null);
    }

    @Override
    public List<TreeSelectModel> queryListByPid(String pid) {
        if (oConvertUtils.isEmpty(pid)) {
            pid = ROOT_PID_VALUE;
        }
        return baseMapper.queryListByPid(pid, null);
    }

    @Override
    public List<TreeSelectModel> queryListByPid(String pid, Map<String, String> condition) {
        if (oConvertUtils.isEmpty(pid)) {
            pid = ROOT_PID_VALUE;
        }
        return baseMapper.queryListByPid(pid, condition);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteCommonClassify(String ids) {
        String allIds = this.queryTreeChildIds(ids);
        String pids = this.queryTreePids(ids);
        //1.删除时将节点下所有子节点一并删除
        this.baseMapper.deleteBatchIds(Arrays.asList(allIds.split(",")));
        //2.将父节点中已经没有下级的节点，修改为没有子节点
        if (oConvertUtils.isNotEmpty(pids)) {
            LambdaUpdateWrapper<CommonClassify> updateWrapper = new UpdateWrapper<CommonClassify>().lambda().in(CommonClassify::getId, Arrays.asList(pids.split(","))).set(CommonClassify::getHasChild, "0");
            this.update(updateWrapper);
        }
    }

    /**
     * 查询节点下所有子节点
     *
     * @param ids
     * @return
     */
    private String queryTreeChildIds(String ids) {
        //获取id数组
        String[] idArr = ids.split(",");
        StringBuffer sb = new StringBuffer();
        for (String pidVal : idArr) {
            if (pidVal != null) {
                if (!sb.toString().contains(pidVal)) {
                    if (sb.toString().length() > 0) {
                        sb.append(",");
                    }
                    sb.append(pidVal);
                    this.getTreeChildIds(pidVal, sb);
                }
            }
        }
        return sb.toString();
    }

    /**
     * 查询需修改标识的父节点ids
     *
     * @param ids
     * @return
     */
    private String queryTreePids(String ids) {
        StringBuffer sb = new StringBuffer();
        //获取id数组
        String[] idArr = ids.split(",");
        for (String id : idArr) {
            if (id != null) {
                CommonClassify category = this.baseMapper.selectById(id);
                //根据id查询pid值
                String metaPid = category.getPid();
                //查询此节点上一级是否还有其他子节点
                LambdaQueryWrapper<CommonClassify> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(CommonClassify::getPid, metaPid);
                queryWrapper.notIn(CommonClassify::getId, Arrays.asList(idArr));
                List<CommonClassify> dataList = this.baseMapper.selectList(queryWrapper);
                boolean flag = (dataList == null || dataList.size() == 0) && !Arrays.asList(idArr).contains(metaPid) && !sb.toString().contains(metaPid);
                if (flag) {
                    //如果当前节点原本有子节点 现在木有了，更新状态
                    sb.append(metaPid).append(",");
                }
            }
        }
        if (sb.toString().endsWith(SymbolConstant.COMMA)) {
            sb = sb.deleteCharAt(sb.length() - 1);
        }
        return sb.toString();
    }

    /**
     * 递归 根据父id获取子节点id
     *
     * @param pidVal
     * @param sb
     * @return
     */
    private StringBuffer getTreeChildIds(String pidVal, StringBuffer sb) {
        LambdaQueryWrapper<CommonClassify> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CommonClassify::getPid, pidVal);
        List<CommonClassify> dataList = baseMapper.selectList(queryWrapper);
        if (dataList != null && dataList.size() > 0) {
            for (CommonClassify category : dataList) {
                if (!sb.toString().contains(category.getId())) {
                    sb.append(",").append(category.getId());
                }
                this.getTreeChildIds(category.getId(), sb);
            }
        }
        return sb;
    }

    @Override
    public List<String> loadDictItem(String ids) {
        return this.loadDictItem(ids, true);
    }

    @Override
    public List<String> loadDictItem(String ids, boolean delNotExist) {
        String[] idArray = ids.split(",");
        LambdaQueryWrapper<CommonClassify> query = new LambdaQueryWrapper<>();
        query.in(CommonClassify::getId, Arrays.asList(idArray));
        // 查询数据
        List<CommonClassify> list = super.list(query);
        // 取出name并返回
        List<String> textList;
        // update-begin--author:sunjianlei--date:20210514--for：新增delNotExist参数，设为false不删除数据库里不存在的key ----
        if (delNotExist) {
            textList = list.stream().map(CommonClassify::getName).collect(Collectors.toList());
        } else {
            textList = new ArrayList<>();
            for (String id : idArray) {
                List<CommonClassify> res = list.stream().filter(i -> id.equals(i.getId())).collect(Collectors.toList());
                textList.add(res.size() > 0 ? res.get(0).getName() : id);
            }
        }
        // update-end--author:sunjianlei--date:20210514--for：新增delNotExist参数，设为false不删除数据库里不存在的key ----
        return textList;
    }


    /**
     * 分页列表查询
     * @param sysCategory
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */

    @Override
    public Result<IPage<CommonClassify>> queryPageList(CommonClassify sysCategory,
                                                       @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                       @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                       HttpServletRequest req) {
        if(oConvertUtils.isEmpty(sysCategory.getPid())){
            sysCategory.setPid("0");
        }
        Result<IPage<CommonClassify>> result = new Result<IPage<CommonClassify>>();
        //------------------------------------------------------------------------------------------------
        //是否开启系统管理模块的多租户数据隔离【SAAS多租户模式】
        if(MybatisPlusSaasConfig.OPEN_SYSTEM_TENANT_CONTROL){
            sysCategory.setTenantId(oConvertUtils.getInt(TenantContext.getTenant(),0));
        }
        //------------------------------------------------------------------------------------------------

        //--author:os_chengtgen---date:20190804 -----for: 分类字典页面显示错误,issues:377--------start
        //--author:liusq---date:20211119 -----for: 【vue3】分类字典页面查询条件配置--------start
        QueryWrapper<CommonClassify> queryWrapper = QueryGenerator.initQueryWrapper(sysCategory, req.getParameterMap());
        String name = sysCategory.getName();
        //QueryWrapper<SysCategory> queryWrapper = new QueryWrapper<SysCategory>();
        if(StringUtils.isBlank(name)){
            queryWrapper.eq("pid", sysCategory.getPid());
        }
        //--author:liusq---date:20211119 -----for: 分类字典页面查询条件配置--------end
        //--author:os_chengtgen---date:20190804 -----for:【vue3】 分类字典页面显示错误,issues:377--------end

        Page<CommonClassify> page = new Page<CommonClassify>(pageNo, pageSize);
        IPage<CommonClassify> pageList = page(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    @Override
    public Result<List<CommonClassify>> queryPageList(CommonClassify sysCategory, HttpServletRequest req) {
        //------------------------------------------------------------------------------------------------
        //是否开启系统管理模块的多租户数据隔离【SAAS多租户模式】
        if(MybatisPlusSaasConfig.OPEN_SYSTEM_TENANT_CONTROL){
            sysCategory.setTenantId(oConvertUtils.getInt(TenantContext.getTenant(), 0));
        }
        //------------------------------------------------------------------------------------------------
        Result<List<CommonClassify>> result = new Result<List<CommonClassify>>();
        QueryWrapper<CommonClassify> queryWrapper = QueryGenerator.initQueryWrapper(sysCategory, req.getParameterMap());
        List<CommonClassify> list =list(queryWrapper);
        result.setSuccess(true);
        result.setResult(list);
        return result;
    }


    /**
     *   添加
     * @param sysCategory
     * @return
     */
    @Override
    public Result<CommonClassify> add(@RequestBody CommonClassify sysCategory) {
        Result<CommonClassify> result = new Result<CommonClassify>();
        try {
            addCommonClassify(sysCategory);
            result.success("添加成功！");
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            result.error500("操作失败");
        }
        return result;
    }

    /**
     *  编辑
     * @param sysCategory
     * @return
     */
    @Override
    public Result<CommonClassify> edit(@RequestBody CommonClassify sysCategory) {
        Result<CommonClassify> result = new Result<CommonClassify>();
        CommonClassify sysCategoryEntity = getById(sysCategory.getId());
        if(sysCategoryEntity==null) {
            result.error500("未找到对应实体");
        }else {
            updateCommonClassify(sysCategory);
            result.success("修改成功!");
        }
        return result;
    }

    /**
     *   通过id删除
     * @param id
     * @return
     */
    @Override
    public Result<CommonClassify> delete(@RequestParam(name = "id", required = true) String id) {
        Result<CommonClassify> result = new Result<CommonClassify>();
        CommonClassify sysCategory = getById(id);
        if(sysCategory==null) {
            result.error500("未找到对应实体");
        }else {
            this.deleteCommonClassify(id);
            result.success("删除成功!");
        }

        return result;
    }

    /**
     *  批量删除
     * @param ids
     * @return
     */
    @Override
    public Result<CommonClassify> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        Result<CommonClassify> result = new Result<CommonClassify>();
        if(ids==null || "".equals(ids.trim())) {
            result.error500("参数不识别！");
        }else {
            deleteCommonClassify(ids);
            result.success("删除成功!");
        }
        return result;
    }

    /**
     * 通过id查询
     * @param id
     * @return
     */
    @Override
    public Result<CommonClassify> queryById(@RequestParam(name = "id", required = true) String id) {
        Result<CommonClassify> result = new Result<CommonClassify>();
        CommonClassify sysCategory = getById(id);
        if(sysCategory==null) {
            result.error500("未找到对应实体");
        }else {
            result.setResult(sysCategory);
            result.setSuccess(true);
        }
        return result;
    }

    /**
     * 导出excel
     *
     * @param request
     */
    @Override
    public ModelAndView exportXls(HttpServletRequest request, CommonClassify sysCategory) {
        //------------------------------------------------------------------------------------------------
        //是否开启系统管理模块的多租户数据隔离【SAAS多租户模式】
        if(MybatisPlusSaasConfig.OPEN_SYSTEM_TENANT_CONTROL){
            sysCategory.setTenantId(oConvertUtils.getInt(TenantContext.getTenant(), 0));
        }
        //------------------------------------------------------------------------------------------------

        // Step.1 组装查询条件查询数据
        QueryWrapper<CommonClassify> queryWrapper = QueryGenerator.initQueryWrapper(sysCategory, request.getParameterMap());
        List<CommonClassify> pageList = list(queryWrapper);
        // Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        // 过滤选中数据
        String selections = request.getParameter("selections");
        if(oConvertUtils.isEmpty(selections)) {
            mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        }else {
            List<String> selectionList = Arrays.asList(selections.split(","));
            List<CommonClassify> exportList = pageList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
            mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
        }
        //导出文件名称
        mv.addObject(NormalExcelConstants.FILE_NAME, "分类字典列表");
        mv.addObject(NormalExcelConstants.CLASS, CommonClassify.class);
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("分类字典列表数据", "导出人:"+user.getRealname(), "导出信息"));
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @Override
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) throws IOException{
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        // 错误信息
        List<String> errorMessage = new ArrayList<>();
        int successLines = 0, errorLines = 0;
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 获取上传文件对象
            MultipartFile file = entity.getValue();
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<CommonClassify> listSysCategorys = ExcelImportUtil.importExcel(file.getInputStream(), CommonClassify.class, params);
                //按照编码长度排序
               // Collections.sort(listSysCategorys);
                log.info("排序后的list====>",listSysCategorys);
                for (int i = 0; i < listSysCategorys.size(); i++) {
                   /* CommonClassify sysCategoryExcel = listSysCategorys.get(i);
                    if(code.length()>3){
                        String pCode = sysCategoryExcel.getCode().substring(0,code.length()-3);
                        log.info("pCode====>",pCode);
                        String pId=sysCategoryService.queryIdByCode(pCode);
                        log.info("pId====>",pId);
                        if(StringUtils.isNotBlank(pId)){
                            sysCategoryExcel.setPid(pId);
                        }
                    }else{
                        sysCategoryExcel.setPid("0");
                    }
                    try {
                        save(sysCategoryExcel);
                        successLines++;
                    } catch (Exception e) {
                        errorLines++;
                        String message = e.getMessage().toLowerCase();
                        int lineNumber = i + 1;
                        // 通过索引名判断出错信息
                        if (message.contains(CommonConstant.SQL_INDEX_UNIQ_CATEGORY_CODE)) {
                            errorMessage.add("第 " + lineNumber + " 行：分类编码已经存在，忽略导入。");
                        }  else {
                            errorMessage.add("第 " + lineNumber + " 行：未知错误，忽略导入");
                            log.error(e.getMessage(), e);
                        }
                    }*/
                }
            } catch (Exception e) {
                errorMessage.add("发生异常：" + e.getMessage());
                log.error(e.getMessage(), e);
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return ImportExcelUtil.imporReturnRes(errorLines,successLines,errorMessage);
    }



    /**
     * 加载单个数据 用于回显
     */
    @Override
    public Result<CommonClassify> loadOne(@RequestParam(name = "field") String field, @RequestParam(name = "val") String val) {
        Result<CommonClassify> result = new Result<CommonClassify>();
        try {
            //update-begin-author:taoyan date:2022-5-6 for: issues/3663 sql注入问题
            boolean isClassField = SqlInjectionUtil.isClassField(field, CommonClassify.class);
            if (!isClassField) {
                return Result.error("字段无效，请检查!");
            }
            //update-end-author:taoyan date:2022-5-6 for: issues/3663 sql注入问题
            QueryWrapper<CommonClassify> query = new QueryWrapper<CommonClassify>();
            query.eq(field, val);
            List<CommonClassify> ls = list(query);
            if(ls==null || ls.size()==0) {
                result.setMessage("查询无果");
                result.setSuccess(false);
            }else if(ls.size()>1) {
                result.setMessage("查询数据异常,["+field+"]存在多个值:"+val);
                result.setSuccess(false);
            }else {
                result.setSuccess(true);
                result.setResult(ls.get(0));
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setMessage(e.getMessage());
            result.setSuccess(false);
        }
        return result;
    }

    /**
     * 加载节点的子数据
     */
    @Override
    public Result<List<TreeSelectModel>> loadTreeChildren(@RequestParam(name = "pid") String pid) {
        Result<List<TreeSelectModel>> result = new Result<List<TreeSelectModel>>();
        try {
            List<TreeSelectModel> ls = queryListByPid(pid);
            result.setResult(ls);
            result.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            result.setMessage(e.getMessage());
            result.setSuccess(false);
        }
        return result;
    }

    /**
     * 加载一级节点/如果是同步 则所有数据
     */
    @Override
    public Result<List<TreeSelectModel>> loadTreeRoot(@RequestParam(name = "async") Boolean async, @RequestParam(name = "pid") String pid) {
        pid = StringUtils.isBlank(pid) ? ROOT_PID_VALUE : pid;
        Result<List<TreeSelectModel>> result = new Result<List<TreeSelectModel>>();
        try {
            List<TreeSelectModel> ls = queryListByPid(pid);
            if(!async) {
                loadAllCategoryChildren(ls);
            }
            result.setResult(ls);
            result.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            result.setMessage(e.getMessage());
            result.setSuccess(false);
        }
        return result;
    }


    /**
     * 递归求子节点 同步加载用到
     */
    @Override
    public void loadAllCategoryChildren(List<TreeSelectModel> ls) {
        for (TreeSelectModel tsm : ls) {
            List<TreeSelectModel> temp = queryListByPid(tsm.getKey());
            if(temp!=null && temp.size()>0) {
                tsm.setChildren(temp);
                loadAllCategoryChildren(temp);
            }
        }
    }



    /**
     * 分类字典树控件 加载节点
     * @param pid
     * @param condition
     * @return
     */
    @Override
    public Result<List<TreeSelectModel>> loadDict(@RequestParam(name = "pid", required = false) String pid, @RequestParam(name = "condition", required = false) String condition) {
        Result<List<TreeSelectModel>> result = new Result<List<TreeSelectModel>>();
        //pid如果传值了 就忽略pcode的作用
        pid = StringUtils.isBlank(pid) ? ROOT_PID_VALUE : pid;
        Map<String, String> query = null;
        if(oConvertUtils.isNotEmpty(condition)) {
            query = JSON.parseObject(condition, Map.class);
        }
        List<TreeSelectModel> ls = queryListByPid(pid,query);
        result.setSuccess(true);
        result.setResult(ls);
        return result;
    }


    /**
     * [列表页面]加载分类字典数据 用于值的替换
     * @param code
     * @return
     */
    @Override
    public Result<List<DictModel>> loadAllData(@RequestParam(name = "code", required = true) String code) {
        Result<List<DictModel>> result = new Result<List<DictModel>>();
        LambdaQueryWrapper<CommonClassify> query = new LambdaQueryWrapper<CommonClassify>();
        List<CommonClassify> list = list(query);
        if(list==null || list.size()==0) {
            result.setMessage("无数据,参数有误.[code]");
            result.setSuccess(false);
            return result;
        }
        List<DictModel> rdList = new ArrayList<DictModel>();
        for (CommonClassify c : list) {
            rdList.add(new DictModel(c.getId(),c.getName()));
        }
        result.setSuccess(true);
        result.setResult(rdList);
        return result;
    }

    /**
     * 根据父级id批量查询子节点
     * @param parentIds
     * @return
     */
    @Override
    public Result getChildListBatch(@RequestParam("parentIds") String parentIds) {
        try {
            QueryWrapper<CommonClassify> queryWrapper = new QueryWrapper<>();
            List<String> parentIdList = Arrays.asList(parentIds.split(","));
            queryWrapper.in("pid", parentIdList);
            List<CommonClassify> list = list(queryWrapper);
            IPage<CommonClassify> pageList = new Page<>(1, 10, list.size());
            pageList.setRecords(list);
            return Result.OK(pageList);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error("批量查询子节点失败：" + e.getMessage());
        }
    }
}
